package com.declum.archon.chunkserver.manager.disk.streams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This Class mainly has static methods that are required when manipulating with
 * Files in Chunk Server.
 * 
 * @author Clement
 * 
 */
public class FileUtils {
	/**
	 * This Verify whether the given path is pointing to a File or Directory.
	 * 
	 * @param file
	 *            file to be checked
	 * @throws FileNotFoundException
	 *             If the path does not exists
	 * @throws IOException
	 *             If any it points to a Directory
	 */
	public static void existsAndBeFile(File file) throws IOException {
		/**
		 * If the file does not exists
		 */
		if (!file.exists()) {
			throw new FileNotFoundException(file.getAbsolutePath()
					+ " not found");
		}

		/**
		 * If its not a file
		 */
		if (!file.isFile()) {
			throw new IOException(file.getAbsolutePath() + " is not a file");
		}
	}

	/**
	 * This Verify whether the given path is pointing to a File or Directory.
	 * 
	 * @param filePath
	 *            file to be checked
	 * @throws FileNotFoundException
	 *             If the path does not exists
	 * @throws IOException
	 *             If any it points to a Directory
	 */
	public static void existsAndBeFile(String filePath) throws IOException {
		/**
		 * Invoke existsAndBeFile(File file)
		 */
		FileUtils.existsAndBeFile(new File(filePath));
	}

	/**
	 * Calculates Checksum for the Given byte array
	 * 
	 * @param buffer
	 *            checksum to be calculated
	 * @return checksum value
	 */
	public static int getCheckSumFotBuffer(byte[] buffer) {
		int checkSum = 0;
		/**
		 * Now, Checksum is the Sum of each bytes in the Array. May be in future
		 * we use very very complex algorithm to do. :-):-):-):-)
		 */
		for (byte b : buffer) {
			checkSum += b;
		}
		return checkSum;
	}

	/**
	 * It calculates the checksum file path for given chunk file
	 * 
	 * @param chunkPath
	 *            chunk file path
	 * @return lock file path
	 */
	public static String getCheckSumFileNameFromChunkPath(String chunkPath) {
		/**
		 * This is an very complex calculation which has artificial intelligent
		 * to predict what will be the path for CheckSum. Don't get scared
		 */
		return chunkPath + ".checksum";
	}
}
